import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:short_drama/models/profit_model.dart';
import 'package:short_drama/models/profit_item_model.dart';
import 'package:short_drama/utils/colors.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:short_drama/utils/http_util.dart';
import 'package:short_drama/utils/float.dart';

class ProfitPage extends StatefulWidget {
  const ProfitPage({Key? key}) : super(key: key);

  State<ProfitPage> createState() => _ProfitPageState();
}

class _ProfitPageState extends State<ProfitPage> {
  final RefreshController _controller = RefreshController();
  List<ProfitItemModel>? _listDatas = [];
  bool _isLoading = true;
  int page = 1;

  @override
  void initState() {
    super.initState();
    _fetchData();
  }

  Future<void> _fetchData() async {
    try {
      final data = await ProfitViewModel.fetchProfitData(page);
      print(data);
      setState(() {
        if (data.length > 0) {
          _listDatas!.addAll(data);
        }
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ClientColors.ff0a0f12,
      appBar: AppBar(
        iconTheme: IconThemeData(color: Colors.white),
        leading: IconButton(
          onPressed: () => {Get.back()},
          icon: Icon(Icons.arrow_back_ios),
        ),
        backgroundColor: ClientColors.odffffff,
        centerTitle: false,
        titleSpacing: FloatConstance.navBarSpace,
        title: Text(
          '认购列表',
          style: TextStyle(color: Colors.white, fontSize: 18),
        ),
      ),
      body:
          _isLoading
              ? Center(child: CircularProgressIndicator())
              : SmartRefresher(
                controller: _controller,
                enablePullUp: true,
                enablePullDown: false,
                onLoading: () {
                  page++;
                  _fetchData();
                  _controller.loadComplete();
                },
                child: ListView.builder(
                  itemCount: _listDatas?.length ?? 0,
                  itemBuilder: (context, index) {
                    final item = _listDatas?[index];
                    return Container(
                      margin: EdgeInsets.only(
                        top: (index == 0) ? 20 : 10,
                        left: 16,
                        right: 16,
                      ),
                      height: 70,
                      padding: EdgeInsets.all(10),
                      decoration: BoxDecoration(
                        color: ClientColors.odffffff,
                        borderRadius: BorderRadius.circular(10),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text(
                                item!.order_name,
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                ),
                              ),
                              Text(
                                '+${item.order_bean}',
                                style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 15,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 10),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Expanded(child: Container()),
                              Text(
                                item.create_time,
                                style: TextStyle(
                                  color: ClientColors.aaffffff,
                                  fontSize: 11,
                                ),
                              ),
                            ],
                          ),
                        ],
                      ),
                    );
                  },
                ),
              ),
    );
  }
}

class ProfitViewModel {
  static Future<List<ProfitItemModel>> fetchProfitData(int page) async {
    try {
      final result = await HttpUtil().get(
        'drama/order/list',
        params: {'page': page, 'limit': 10},
      );
      final responseData = result.data?['data'];
      if (responseData == null) {
        throw Exception('响应数据格式错误: 缺少data字段');
      }

      final rawList = responseData['data'] as List?;
      if (rawList == null) {
        return [];
      }
      return rawList
          .map((e) => ProfitItemModel.fromJson(e as Map<String, dynamic>))
          .toList();
    } catch (e) {
      print('获取分页数据异常: $e');
      rethrow;
    }
  }
}
